using AutoMapper;
using B.S.RbacData.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SupplierCustomerManagement.Domain.Entities;
using B.S.RbacData.ErrorCode;
using SupplierCustomerManagement.Write.API.Applications.Commands.suppliercontacts;

namespace SupplierCustomerManagement.Write.API.Applications.CommandHandlters.suppliercontacts
{
    /// <summary>
    /// 修改供应商联系人命令处理器
    /// </summary>
    public class UpdateSupplierContactCommandHandler : IRequestHandler<UpdateSupplierContactCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<SupplierContact> _supplierContactRepository;
        private readonly IBaseRepository<Supplier> _supplierRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<UpdateSupplierContactCommandHandler> _logger;

        public UpdateSupplierContactCommandHandler(
            IBaseRepository<SupplierContact> supplierContactRepository,
            IBaseRepository<Supplier> supplierRepository,
            IMapper mapper,
            ILogger<UpdateSupplierContactCommandHandler> logger)
        {
            _supplierContactRepository = supplierContactRepository;
            _supplierRepository = supplierRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理修改供应商联系人命令
        /// </summary>
        /// <param name="request">修改供应商联系人命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult<bool>> Handle(UpdateSupplierContactCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证供应商联系人是否存在
                var existingContact = await _supplierContactRepository.GetAll()
                    .FirstOrDefaultAsync(c => c.Id == request.Id && !c.IsDeleted, cancellationToken);

                if (existingContact == null)
                {
                    return ApiResult<bool>.Error("供应商联系人不存在");
                }

                // 验证供应商是否存在
                var supplier = await _supplierRepository.GetAll()
                    .FirstOrDefaultAsync(s => s.Id == request.SupplierId && !s.IsDeleted, cancellationToken);

                if (supplier == null)
                {
                    return ApiResult<bool>.Error("供应商不存在");
                }

                // 验证联系人姓名是否已存在（同一供应商下，排除当前记录）
                var duplicateContact = await _supplierContactRepository.GetAll()
                    .FirstOrDefaultAsync(c => c.SupplierId == request.SupplierId && 
                                             c.ContactPerson == request.ContactPerson && 
                                             c.Id != request.Id && 
                                             !c.IsDeleted, cancellationToken);

                if (duplicateContact != null)
                {
                    return ApiResult<bool>.Error("该供应商下已存在同名联系人");
                }

                // 如果设置为默认联系人，需要将其他联系人设置为非默认
                if (request.IsDefault && !existingContact.IsDefault)
                {
                    var existingDefaultContacts = await _supplierContactRepository.GetAll()
                        .Where(c => c.SupplierId == request.SupplierId && 
                                   c.IsDefault && 
                                   c.Id != request.Id && 
                                   !c.IsDeleted)
                        .ToListAsync(cancellationToken);

                    foreach (var contact in existingDefaultContacts)
                    {
                        contact.IsDefault = false;
                        contact.UpdatedTime = DateTime.Now;
                        contact.UpdatedBy = request.UpdatedBy;
                        await _supplierContactRepository.UpdateAsync(contact);
                    }
                }

                // 使用AutoMapper更新实体属性
                _mapper.Map(request, existingContact);

                // 设置更新时间
                existingContact.UpdatedTime = DateTime.Now;
                existingContact.UpdatedBy = request.UpdatedBy;

                // 更新供应商联系人
                var result = await _supplierContactRepository.UpdateAsync(existingContact);

                if (result > 0)
                {
                    _logger.LogInformation("成功修改供应商联系人，ID: {ContactId}, 供应商ID: {SupplierId}, 联系人: {ContactPerson}", 
                        existingContact.Id, existingContact.SupplierId, existingContact.ContactPerson);
                    
                    return ApiResult<bool>.Success(true, "供应商联系人修改成功");
                }
                else
                {
                    _logger.LogError("修改供应商联系人失败，ID: {ContactId}, 联系人: {ContactPerson}", 
                        request.Id, request.ContactPerson);
                    
                    return ApiResult<bool>.Error("供应商联系人修改失败");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "修改供应商联系人时发生异常，ID: {ContactId}, 联系人: {ContactPerson}", 
                    request.Id, request.ContactPerson);
                
                return ApiResult<bool>.Error($"修改供应商联系人时发生异常: {ex.Message}");
            }
        }
    }
} 